<template>
  <base-page-view class-name="page-container material-publish-container">
    <!-- 自定义nav -->
    <base-nav title="发布种草" left-icon="back" left-icon-pic="icon_arror_left" :left-click="leftClick"></base-nav>

    <!-- 表单 -->
    <view class="form-block">
      <view class="form-item flex">
        <input v-model="formData.title" class="sub-item" maxlength="30" placeholder-style="font-size:26rpx;color:#C5C5C5;" placeholder="填写标题要突出你的作品主题喔~" @blur="titleBlur" />
        <text class="text">{{ formData.title.length }}/30</text>
      </view>
      <view class="form-item">
        <view class="content">
          <textarea v-model="formData.content" placeholder-style="font-size:26rpx;color:#C5C5C5;" maxlength="800" placeholder="介绍一下你的作品与分享心得吧,越详细越容易热门~" />
        </view>
        <view class="resource">
          <!-- 图片/视频 -->
          <view v-for="(item, index) in formData.resourceObjectList" :key="index" class="resource-item">
            <template v-if="item.resourceType===1">
              <image class="img" :src="item.resourceUrl + rotateUrl" mode="aspectFill" @click="showPreviewImg(index)"></image>
              <image class="icon-del" src="/static/images/icon/icon_del.png" @click.stop="delResource(index)" />
            </template>
            <template v-else-if="item.resourceType===2">
              <image class="img" :src="item.videoPreviewImg || formData.cover" mode="aspectFill"></image>
              <view class="play-button" @click.stop.prevent="videoSrc = item.resourceUrl">
                <image class="icon-play" src="/static/images/order/icon_evaluate_play.png" />
              </view>
              <image class="icon-del" src="/static/images/icon/icon_del.png" @click.stop="delResource(index)" />
            </template>
          </view>
          <!-- 上传按钮 -->
          <view v-if="showUploadBtn" class="resource-item" @click="pShow = true">
            <image class="img" src="/static/images/publish/file.png"></image>
            <view class="imgText">{{ formData.resourceObjectList.length === 0?'图片/视频':'已添加'+formData.resourceObjectList.length+'/9' }}</view>
          </view>
        </view>
        <view class="tag-block">
          <view class="tag-title">#请选择标签</view>
          <view class="tag-list">
            <view v-for="(item, index) in tagList" :key="index" class="tag-item" :class="{ active: item.selected }" @click="tagClick(index)">#{{ item.title }}#</view>
          </view>
        </view>
      </view>
      <view v-if="optionState.length < 5" class="form-item flex" @click="$navigateTo('/pagesPublic/search/index?type=pagesMaterial')">
        <view class="sub-item">+添加推荐商品/套餐</view>
        <image class="icon-right" src="@/static/images/icon/icon_arror_right.png" alt="" />
      </view>
      <!-- 商品/套餐 列表 -->
      <view class="goods-list">
        <view v-for="(item, index) in optionState" :key="index" class="goods-item-container">
          <goods-item class-name="goods-item" image-radius="0" :goods-data="item" delet-type="imageDelete"></goods-item>
        </view>
      </view>
      <!-- 发布按钮 -->
      <view class="publish-btn">
        <button type="primary" class="btnColor" @click="publish">发布</button>
      </view>
    </view>

    <!-- 播放视频 -->
    <view v-if="videoSrc" class="mask-video-box">
      <video :src="videoSrc" class="mask-video" autoplay>
        <cover-image class="close" src="/static/images/icon/icon_return_white.png" @click="videoSrc = ''"></cover-image>
      </video>
    </view>

    <!-- 图片/视频上传选择 -->
    <base-popup :show="pShow" :show-close="false" @close="closePopup">
      <view class="upload-popup">
        <view class="select-box">
          <view class="select-item" @click="upload('chooseVideo')">视频</view>
          <view class="select-item" @click="upload('chooseImage')">图片</view>
        </view>
        <view class="select-box">
          <view class="select-item" @click="closePopup">取消</view>
        </view>
      </view>
    </base-popup>

    <!-- 发布成功弹窗 -->
    <bottomPopup ref="showPopup" :success-list="successList" :tag-popup-list="tagPopupList" :from="from"></bottomPopup>

    <!-- 确认对话框组件 -->
    <confirm-popup ref="confirm"></confirm-popup>
  </base-page-view>
</template>
<script>
import { mapState } from 'vuex'
import confirmPopup from '@/components/confirmPopup/index'
import goodsItem from '@/components/goodsItem/index.vue'
import basePopup from '@/components/base/base-popup.vue'
import bottomPopup from './bottomPopup/index'
import { debounce } from '@/utils/tools'
import './index.scss'
export default {
  name: '',
  components: { confirmPopup, goodsItem, basePopup, bottomPopup },
  data() {
    return {
      from: 'moment', // moment: 素材圈首页、mine: 个人主页
      rotateUrl: '?x-oss-process=image/rotate,0',
      videoSrc: '',
      tagList: [],
      pShow: false,
      successList: [],
      tagPopupList: [],
      formData: {
        id: '',
        categoryType: 4,
        type: 4,
        title: '',
        content: '',
        resourceObjectList: [],
        tags: []
      }
    }
  },
  computed: {
    ...mapState(['optionState']),
    showUploadBtn: function() {
      const imageList = this.formData.resourceObjectList.filter(i => i.resourceType === 1)
      const videoList = this.formData.resourceObjectList.filter(i => i.resourceType === 2)
      return !(videoList.length === 1 || imageList.length === 9)
    }
  },
  onLoad(option) {
    this.formData.id = option.id || ''
    this.from = option.from || 'mine'
    this.$store.commit('PRODUCT_DATA', [])

    if (this.formData.id) {
      this.fetchData()
    } else {
      this.fetchTagData()
    }
  },
  onReady() {
    setTimeout(this.checkStore, 300)
  },
  methods: {
    // 获取素材详情
    async fetchData() {
      const res = await this.$api.materialApi.getMaterialDetail({ id: this.formData.id })
      if (res.success && res.data) {
        const { id, type, title, content, category_ids, goods, resource_object_list } = res.data
        this.formData = {
          id,
          type,
          categoryType: 4,
          title,
          content,
          tags: category_ids || [],
          goods,
          resourceObjectList: resource_object_list || []
        }
        this.$store.commit('PRODUCT_DATA', goods || [])
      }
      this.fetchTagData()
    },
    // 获取标签
    async fetchTagData() {
      const res = await this.$api.materialApi.getMaterialTag()
      if (res.success) {
        this.tagList = (res.data || []).map(i => ({ id: i.id, title: i.title, selected: this.formData.tags.includes(i.id) }))
      }
    },
    // 新建的时候检查草稿箱
    checkStore() {
      if (this.formData.id) {
        return
      }
      uni.getStorage({
        key: 'TEMP_PUBLISH_DATA',
        success: (res) => {
          if (res.data) {
            this.$refs.confirm.show({
              content: '上次有未发布的内容,是否加载?',
              title: '温馨提示',
              cancleTxt: '取消',
              yesTxt: '确定',
              yesCb: async() => {
                this.formData = res.data
                this.$store.commit('PRODUCT_DATA', this.formData.goods || [])

                this.fetchTagData()
              }
            })
          }
        }
      })
    },
    // 点击返回
    leftClick() {
      let $this = this
      // #ifdef MP-WEIXIN
      $this = this.$parent.$parent
      // #endif
      $this.formData.tags = []
      $this.tagList.map(i => {
        if (i.selected) { $this.formData.tags.push(i.id) }
      })

      $this.formData.goods = $this.optionState.map(i => ({
        ...i,
        id: null
      }))
      if (!$this.formData.id && ($this.formData.title || $this.formData.content || $this.formData.resourceObjectList.length || $this.formData.tags.length)) {
        $this.$refs.confirm.show({
          content: '有编辑内容,确定放弃发布',
          title: '温馨提示',
          cancleTxt: '取消',
          yesTxt: '确定',
          yesCb: async() => {
            uni.setStorage({
              key: 'TEMP_PUBLISH_DATA',
              data: $this.formData
            })
            uni.navigateBack()
          }
        })
      } else {
        uni.navigateBack()
      }
    },
    // 标题输入框失焦验证
    titleBlur(e) {
      if (e.detail.value.length < 2 && e.detail.value.length > 0) {
        uni.showToast({
          title: '标题不少于2个字',
          icon: 'none',
          duration: 2000
        })
      }
    },
    // 图片预览
    showPreviewImg(index) {
      const imgList = []
      this.formData.resourceObjectList.forEach(item => {
        imgList.push(item.resourceUrl)
      })
      uni.previewImage({
        current: index,
        urls: imgList
      })
    },
    // 删除图片/视频
    delResource(index) {
      this.formData.resourceObjectList.splice(index, 1)
    },
    closePopup() {
      this.pShow = false
    },
    // 图片/视频上传
    async upload(type) {
      let count = 1
      if (type === 'chooseImage') {
        count = 9 - this.formData.resourceObjectList.length
      }

      this.closePopup()
      const res = await this.$api.commonApi.uploadImg({ count, info: 1, type, limit: true })
      if (res.success) {
        const list = (res.url || []).map(i => ({
          resourceType: type === 'chooseImage' ? 1 : 2,
          resourceUrl: i.url,
          videoPicUrl: i.cover || '',
          videoPreviewImg: i.cover || '',
          width: i.imgInfo ? i.imgInfo.width : 750,
          height: i.imgInfo ? i.imgInfo.height : 750
        }))
        if (type === 'chooseVideo') {
          this.formData.resourceObjectList = []
        }
        this.formData.resourceObjectList = this.formData.resourceObjectList.concat(list)
      }
      //
    },
    tagClick(index) {
      this.$set(this.tagList[index], 'selected', !this.tagList[index].selected)
    },
    // 点击发布
    publish: debounce(async function() {
      this.formData.tags = []
      this.tagList.map(i => {
        if (i.selected) { this.formData.tags.push(i.id) }
      })
      this.formData.goods = this.optionState.map(i => ({
        ...i,
        id: null
      }))
      this.formData.type = this.formData.resourceObjectList.some(i => i.resourceType === 2) ? 8 : 4
      if (!this.formData.title) {
        uni.showToast({ title: '标题不能为空', icon: 'none', duration: 2000 })
      } else if (this.formData.title.length < 2) {
        uni.showToast({ title: '标题不少于2个字', icon: 'none', duration: 2000 })
      } else if (!this.formData.content) {
        uni.showToast({ title: '内容不能为空', icon: 'none', duration: 2000 })
      } else if (this.formData.resourceObjectList.length === 0) {
        uni.showToast({ title: '请选择图片或视频', icon: 'none', duration: 2000 })
      } else if (this.formData.tags.length === 0) {
        uni.showToast({ title: '请选择标签', icon: 'none', duration: 2000 })
      } else {
        const res = await this.$api.materialApi.materialSubmit({ ...this.formData })
        if (res.success) {
          this.successList = [
            {
              title: this.formData.title,
              imageSrc: this.formData.resourceObjectList[0].videoPreviewImg || this.formData.resourceObjectList[0].resourceUrl + this.rotateUrl
            }
          ]
          this.tagPopupList = this.tagList.filter(i => i.selected)
          this.$refs.showPopup.handleShowShare()
          if (!this.formData.id) {
            uni.removeStorage({ key: 'TEMP_PUBLISH_DATA' })
          }
        }
      }
    }, 300)
  }
}
</script>
